<?php

namespace App\Http\Controllers\Api;

use App\Common\ErrorCode;
use App\Models\Banner;
use App\Models\Book;
use App\Models\BookComment;
use App\Models\BookList;
use App\Models\BookRecommendPositionRelation;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\User;
use App\Models\UserVipTimeRecord;
use App\Models\UserVipType;
use App\Models\UserWantBook;
use Carbon\Carbon;
use Illuminate\Http\Request;
use DB;

class UsersController extends BaseController
{
    // 登录后保存用户信息
    public function store(Request $request)
    {
        $wechat_openid = $request->input('wechat_openid');
        $wechat_avatar = $request->input('wechat_avatar');
        $wechat_nickname = $request->input('wechat_nickname');
        $share_user_id = intval($request->input('share_user_id'));  //推荐者id

        if(empty($wechat_openid) || empty($wechat_avatar) || empty($wechat_nickname))
        {
            return $this->error(ErrorCode::PARAMS_NOT_VALID_CODE,ErrorCode::PARAMS_NOT_VALID_MESSAGE);
        }

        $user = User::where('wechat_openid',$wechat_openid)->first();
        if(empty($user))
        {
            $user = User::create([
                'wechat_avatar' => $wechat_avatar,
                'wechat_nickname' => $wechat_nickname,
                'wechat_openid' => $wechat_openid,
                'share_user_id' => $share_user_id
            ]);
        }
        else
        {
            User::where('id',$user->id)->update([
                'wechat_avatar' => $wechat_avatar,
                'wechat_nickname' => $wechat_nickname,
            ]);
        }

        return $this->success(['user_id'=>$user->id]);
    }

    public function send_verification_code(Request $request)
    {
        $telephone = $request->input('telephone');
        $user_id = $request->input('user_id');

        if(empty($telephone) || !isMobile($telephone))
        {
            return $this->error(ErrorCode::TELEPHONE_NOT_VALID_CODE,ErrorCode::TELEPHONE_NOT_VALID_MESSAGE);
        }

        //判断手机号是否已经被人绑定
        $user = User::query()->where('telephone',$telephone)->first();
        if(!empty($user))
        {
            return $this->error(ErrorCode::TELEPHONE_BIND_CODE,ErrorCode::TELEPHONE_BIND_MESSAGE);
        }

        // 生成4位随机数，左侧补0
        $code = str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT);

        $sms = app('easysms');
        try {
            $sms->send($telephone,[
                'template' => 'SMS_142388144',
                'data' => [
                    'number' => $code
                ],
            ]);
        } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
            $message = $exception->getException('aliyun')->getMessage();
            dd($message);
        }

        $key = 'verificationCode_'.str_random(15);
        $expiredAt = now()->addMinutes(30);
        // 缓存验证码 10分钟过期。
        \Cache::put($key, ['telephone' => $telephone, 'code' => $code, 'user_id' => $user_id], $expiredAt);

        return $this->res([
            'data' => [
                'key' => $key,
                'expired_at' => $expiredAt->toDateTimeString()
            ]
        ]);
    }

    public function check_telephone(Request $request)
    {
        $user_id = $request->input('user_id');
        if(empty($user_id))
        {
            return $this->error(ErrorCode::PARAMS_NOT_VALID_CODE,ErrorCode::PARAMS_NOT_VALID_MESSAGE);
        }

        $user = User::query()->find($user_id);

        $is_bind = 1;
        if(empty($user->telephone))
        {
            $is_bind = 0;
        }
        return $this->res([
            'data' => [
                'is_bind' => $is_bind,
            ]
        ]);
    }

    public function bind_telephone(Request $request)
    {
        $key = $request->input('key');
        $verification_code = $request->input('verification_code');
        $user_id = $request->input('user_id');

        $verifyData = \Cache::get($key);

        if(empty($verifyData))
        {
            return $this->error(10000,'验证码已失效');
        }

        if($user_id != $verifyData['user_id'])
        {
            return $this->error(10000,'用户错误');
        }

        if (!hash_equals($verifyData['code'], $verification_code))
        {
            return $this->error(10000,'验证码错误');
        }

        $user = User::where('id',$user_id)->update([
            'telephone' => $verifyData['telephone']
        ]);

        // 清除验证码缓存
        \Cache::forget($key);
        return $this->success();
    }

    public function show(User $user)
    {
        //dd($user->book_list_collects);

        if(!$user->is_vip)
        {
            $banner = Banner::query()->where('type',2)->orderBy('id','desc')->first();
        }
        else
        {
            $banner = Banner::query()->where('type',3)->orderBy('id','desc')->first();
        }

        $banner_info = [];
        if(!empty($banner))
        {
            $banner_info = [
                'type' => $banner->type,
                'url' => $banner->url,
                'image' => config('app.qiniu_image_domain').DIRECTORY_SEPARATOR.$banner->image,
            ];
        }

        //计算用户会员天数
        $days = 0;
        if($user->is_vip == 1)
        {
            if(!empty($user->vip_end_time) && !empty($user->vip_start_time))
            {
                $timediff = $user->vip_end_time - $this->time;
                $days = ceil($timediff/86400);
            }
            else
            {
                $days = DB::table('user_vip_orders')->where('user_id',$user->id)->where('is_used',0)->where('status',1)->sum('vip_days');
            }
        }


        return $this->res([
            'data' => [
                'is_vip' => $user->is_vip,
                'wechat_avatar' => $user->wechat_avatar,
                'wechat_nickname' => $user->wechat_nickname,
                'collect_book_list_num' => count($user->book_list_collects),
                'banner' => $banner_info,
                'vip_days' => $days
            ]
        ]);
    }

    public function getVipTypes()
    {
        $types = UserVipType::all();
        $items = [];

        if(!empty($types))
        {
            foreach ($types as $v)
            {
                $items[] = [
                    'type' => $v['type'],
                    'price' => $v['price'],
                    'day_price' => $v['day_price'],
                    'type_str' => UserVipType::$typeMap[$v['type']]
                ];
            }
        }

        return $this->res([
            'data' => $items
        ]);
    }

    public function getVipTimeRecords(Request $request)
    {
        $page = intval($request->input('page',1));
        $per_page = intval($request->input('per_page',20));
        $user_id = intval($request->input('user_id'));

        $list = UserVipTimeRecord::query()->where('user_id',$user_id)->orderBy('id','desc')->paginate($per_page,['id','type','intro','created_at','days'],'page',$page);

        //计算用户会员天数
        $user = User::query()->where('id',$user_id)->first();
        $days = 0;
        $is_open_card = 0;
        if($user->is_vip == 1)
        {
            if(!empty($user->vip_end_time) && !empty($user->vip_start_time))
            {
                $timediff = $user->vip_end_time - $this->time;
                $days = ceil($timediff/86400);

                $is_open_card = 1;
            }
            else
            {
                $days = DB::table('user_vip_orders')->where('user_id',$user->id)->where('is_used',0)->where('status',1)->sum('vip_days');
            }
        }

        $items = [];
        if(!empty($list->items()))
        {
            foreach ($list->items() as $v)
            {
                $items[] = [
                    'id' => $v->id,
                    'type' => $v->type,
                    'intro' => $v->intro,
                    'created_at' => date('Y-m-d H:i',strtotime($v->created_at)),
                    'days' => $v->days,
                ];
            }
        }
        $data = [
            '_meta' => [
                'total_count' => $list->total(),
                'page_count' => $list->lastPage(),
                'current_page' => $list->currentPage(),
                'per_page' => $list->perPage()
            ],
            "items" => $items,
            "vip_days" => $days,
            'is_open_card' => $is_open_card,
            'bind_telephone' => $user->telephone
        ];
        return $this->res([
            'data' => $data
        ]);
    }

    public function getMyCollectBookLists(Request $request)
    {
        $user_id = intval($request->input('user_id'));
        $book_list_ids = DB::table('book_list_user_collect_relations')->where('user_id',$user_id)->where('user_type',1)->pluck('book_list_id');
        //dd($book_list_ids);
        $list = BookList::query()->with(['user_collects'])->select('id','title','list_image','total_collect_num','intro')->whereIn('id',$book_list_ids)->where('deleted',0)->get();

        $items = [];
        if(!empty($list))
        {
            foreach ($list as $v)
            {
                $user_collects = [];
                if(!empty($v->user_collects))
                {
                    foreach ($v->user_collects as $key=>$value)
                    {
                        if($key == 3)
                        {
                            break;
                        }
                        $user_collects[] = [
                            'user_id' => $value['id'],
                            'user_wechat_avatar' => $value['wechat_avatar']
                        ];
                    }
                }

                $book_nums = DB::table('book_list_book_relations')->where('book_list_id',$v['id'])->count();
                $items[] = [
                    'id' => $v['id'],
                    'title' => $v['title'],
                    'intro' => $v['intro'],
                    'total_collect_num' => $v['total_collect_num'],
                    'book_nums' => $book_nums,
                    'list_image' => config('app.qiniu_image_domain').DIRECTORY_SEPARATOR.$v['list_image'],
                    'user_collects' => $user_collects
                ];
            }
        }

        return $this->res([
            'data' => $items
        ]);
    }

    public function my_comments(Request $request)
    {
        $user_id = intval($request->input('user_id'));
        $page = intval($request->input('page',1));
        $per_page = intval($request->input('per_page',20));

        if(empty($user_id))
        {
            return $this->error(ErrorCode::PARAMS_NOT_VALID_CODE,ErrorCode::PARAMS_NOT_VALID_MESSAGE);
        }

        $total_count = BookComment::query()->where('user_id',$user_id)->count();
        $page = max(1,$page);
        $offset = ($page - 1)*$per_page;
        $page_count = ceil($total_count/$per_page);

        $comments = BookComment::query()->with(['book','user'])->where('user_id',$user_id)->offset($offset)->limit($per_page)->orderBy('id','desc')->get();

        $items = [];
        if(!empty($comments))
        {
            foreach ($comments as $v)
            {
                $items[] = [
                    'user_wechat_avatar' => $v->user->wechat_avatar,
                    'user_wechat_nickname' => $v->user->wechat_nickname,
                    'rate' => $v->rate,
                    'status' => $v->status,
                    'content' => $v->content,
                    'created_at' => $v->created_at->toDateTimeString(),
                    'good_num' => $v->good_num,
                    'book_title' => $v->book->title,
                    'book_image' => config('app.qiniu_image_domain').DIRECTORY_SEPARATOR.$v->book->image,
                    'book_author' => $v->book->author,
                    'book_id' => $v->book->id,
                ];
            }
        }

        $order_ids = Order::query()->where('user_id',$user_id)->where('status','>',1)->pluck('id');
        //print_r($order_ids);
        $order_items = OrderItem::query()->with(['book'])->where('is_comment',0)->whereIn('order_id',$order_ids)->get();

        return $this->res([
            'data' => [
                '_meta' => [
                    'total_count' => $total_count,
                    'page_count' => $page_count,
                    'current_page' => $page,
                    'per_page' => $per_page
                ],
                'items' => $items,
                'total_books' => OrderItem::query()->where('user_id',$user_id)->count(),
                //'uncomment_books' => OrderItem::query()->where('user_id',$user_id)->where('is_comment',0)->count()
                'uncomment_books' => count($order_items)
            ]
        ]);
    }

    public function info(Request $request)
    {
        $openid = $request->input('openid');
        if(empty($openid))
        {
            return $this->error(ErrorCode::PARAMS_NOT_VALID_CODE,ErrorCode::PARAMS_NOT_VALID_MESSAGE);
        }

        $user = User::query()->where('wechat_openid',$openid)->first();
        if(!empty($user))
        {
            return $this->res([
                'data' => [
                    'wechat_nickname' => $user->wechat_nickname,
                    'wechat_avatar' => $user->wechat_avatar,
                    'user_id' => $user->id,
                    'wechat_openid' => $user->wechat_openid,
                    'is_vip' => $user->is_vip
                ]
            ]);
        }
        return $this->success();
    }

    public function want_books(Request $request)
    {
        $user_id = intval($request->input('user_id'));
        $title = $request->input('title');
        $author = $request->input('author');

        if(empty($user_id) || empty($title) || empty($author))
        {
            return $this->error(ErrorCode::PARAMS_NOT_VALID_CODE,ErrorCode::PARAMS_NOT_VALID_MESSAGE);
        }

        UserWantBook::create([
            'user_id' => $user_id,
            'title' => $title,
            'author' => $author,
            'created_at' => Carbon::now()
        ]);

        return $this->success();
    }

    public function myInviteUsers(Request $request)
    {
        if(empty($this->user_id))
        {
            return $this->error(ErrorCode::PARAMS_NOT_VALID_CODE,ErrorCode::PARAMS_NOT_VALID_MESSAGE);
        }

        $users = User::query()->where('share_user_id',$this->user_id)->get();

        $items = [];
        if(!empty($users))
        {
            foreach ($users as $v)
            {
                $items[] = [
                    'wechat_nickname' => $v->wechat_nickname,
                    'wechat_avatar' => $v->wechat_avatar,
                    'user_id' => $v->id,
                    'wechat_openid' => $v->wechat_openid,
                    'is_vip' => $v->is_vip,
                    'created_at' => $v->created_at->toDateTimeString()
                ];
            }
        }

        //计算成功邀请的人数和天数
        $persons = UserVipTimeRecord::query()->where('user_id',$this->user_id)->where('type',4)->count();
        $days = UserVipTimeRecord::query()->where('user_id',$this->user_id)->where('type',4)->sum('days');
        return $this->res([
            'data' => [
                'itmes' => $items,
                'persons' => $persons,
                'days' => $days
            ]
        ]);
    }

    public function share_user_info(Request $request)
    {
        if(empty($this->user_id))
        {
            return $this->error(ErrorCode::PARAMS_NOT_VALID_CODE,ErrorCode::PARAMS_NOT_VALID_MESSAGE);
        }

        $user = User::query()->where('id',$this->user_id)->first();


        $ids = OrderItem::query()->where('user_id',$this->user_id)->orderBy('id','desc')->pluck('book_id')->toArray();
        $ids = array_unique($ids);
        //print_r($ids);die;

        //$books = Book::query()->select('id','title','image')->whereIn('id',$ids)->get();
        //dd($books);
        $items = [];
        $books = [];
        if(!empty($ids))
        {
            foreach ($ids as $k=>$i)
            {
                if($k >= 3)
                {
                    continue;
                }
                $books[] = Book::query()->select('id','title','image')->where('id',$i)->first()->toArray();
            }
            //var_dump($books->items);die;
            foreach ($books as $v)
            {
                $items[] =[
                    'title' => $v['title'],
                    'id' => $v['id'],
                    'image' => config('app.qiniu_image_domain').DIRECTORY_SEPARATOR.$v['image'],
                ];
            }
            $status = 1;
        }
        else
        {
            $status = 0;
            //小编力荐
            $ids_arr = BookRecommendPositionRelation::query()->where('book_recommend_position_id',2)->pluck('book_id');
            //print_r($ids_arr);
            $books = Book::query()->select('id','title','author','image','douban_score','category_id','total_read_num','intro')->with(['category'])->whereIn('id',$ids_arr)->limit(3)->orderBy('total_read_num','desc')->get();
            if(!empty($books))
            {
                foreach ($books as $item)
                {
                    $items[] = [
                        'title' => $item->title,
                        'id' => $item->id,
                        'image' => config('app.qiniu_image_domain').DIRECTORY_SEPARATOR.$item->image,
                    ];
                }
            }
        }
        return $this->res([
            'data' => [
                'wechat_nickname' => $user->wechat_nickname,
                'wechat_avatar' => $user->wechat_avatar,
                'user_id' => $user->id,
                'book_num' => OrderItem::query()->where('user_id',$this->user_id)->count(),
                'book_items' => $items,
                'status' => $status
            ]
        ]);
    }
}
